using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ToDoListWeb.Models;
using ToDoListWeb.ViewModels;

namespace ToDoListWeb.Service
{
    public class MatterService
    {
        private ToDoListWebContext _ctx = new ToDoListWebContext();
        UserService _userService = new UserService();
        InventoryService _inventoryService = new InventoryService();
        TypeService _typeService = new TypeService();

        /// <summary>
        /// 创建事件；
        /// 根据所给数据新建一个Matter对象；
        /// 将该对象添加到inventory下的event列表和_ctx下的event列表中；
        /// </summary>
        /// <param name="inventoryId"></param>
        /// <param name="eventContent"></param>
        public void CreateMatter(int inventoryId, string matterContent)                    //创建事件(事件内容)
        {
            Inventory inventory = _ctx.Inventory.SingleOrDefault(p => p.InventoryId == inventoryId);
            Matter notDoneMatter = new Matter()
            {
                UserId = inventory.UserId,
                TypeId = inventory.TypeId,
                InventoryId = inventory.InventoryId,
                CreatTime = DateTime.Now,
                MatterContent = matterContent,
                IsFinished = false,
                IsPastdue = false,
            };
            _ctx.Matter.Add(notDoneMatter);
            _ctx.SaveChanges();
        }
        public void AddMatter(int inventoryId, string matterContent, DateTime overTime)                    //创建事件(事件内容)
        {
            Inventory inventory = _ctx.Inventory.SingleOrDefault(p => p.InventoryId == inventoryId);
            Matter notDoneMatter = new Matter()
            {
                UserId = inventory.UserId,
                TypeId = inventory.TypeId,
                InventoryId = inventory.InventoryId,
                CreatTime = DateTime.Now,
                MatterContent = matterContent,
                IsFinished = false,
                IsPastdue = false,
                OverTime = overTime
            };
            _ctx.Matter.Add(notDoneMatter);
            _ctx.SaveChanges();
        }
       
        /// <summary>
        /// 改变完成状态
        /// </summary>
        /// <param name="inventoryId"></param>
        /// <param name="eventId"></param>
        public void ChangeIsFinished(int matterId)                                       //修改事件完成状态
        {
            var matter = _ctx.Matter.SingleOrDefault(m => m.MatterId == matterId);
            matter.IsFinished = !matter.IsFinished;
            _ctx.SaveChanges();
        }
        
        /// <summary>
        /// 对该userId对应所有Matter进行判断；
        /// 如果对应事件未设置过期时间，事件未过期，IsPastdue设置为false；
        /// 如果对应事件已过期，IsPastdue设置为true;
        /// 如果对应时间未过期，IsPastdue设置为false;
        /// </summary>
        /// <param name="userId"></param>
        public void IsPastdueTime(int userId)                                                   //计算事件是否过期
        {
            foreach (var item in _ctx.Matter.Where(p => p.UserId == userId).ToList())
            {
                if (item.OverTime != null && item.OverTime < DateTime.Now)
                    item.IsPastdue = true;
                else
                    item.IsPastdue = false;
            }
            _ctx.SaveChanges();
        }

        public void DeleteMatter(int matterId)                               //删除事件
        {
            _ctx.Matter.Remove(_ctx.Matter.SingleOrDefault(m => m.MatterId == matterId));
            _ctx.SaveChanges();
        }

        public void CompileMatterModel(int inventoryId, int matterId, string matterContent, string matterRemark, string dateTime)
        {
            var matter = _ctx.Matter.SingleOrDefault(m => m.MatterId == matterId);
            matter.InventoryId = inventoryId;
            if (matterContent != null)
                matter.MatterContent = matterContent;
            if (matterRemark != null)
                matter.Remark = matterRemark;
            if (dateTime != null)
                matter.OverTime = Convert.ToDateTime(dateTime);
            _ctx.SaveChanges();
        }

        public List<Matter> GetAllOfUserMatters(int userId)
        {
            var user = _ctx.Users.Include("Matter").SingleOrDefault(u => u.UserId == userId);
            return user.Matter.ToList();
        }

        public List<Matter> GetMatters(int inventoryId)                                 //获取所有事项
        {
            var matters = _ctx.Inventory.Include("Matter").SingleOrDefault(i => i.InventoryId == inventoryId).Matter.ToList();
            return matters;
        }

        public Matter GetMatter(int matterId)                                           //获取一个事项
        {
            var matter = _ctx.Matter.SingleOrDefault(m => m.MatterId == matterId);
            return matter;
        }
        /// <summary>
        /// ViewModel转化
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<MattersViewModel> ConvertEntityModelToViewModel(int userId)
        {
            var matters = GetAllOfUserMatters(userId);
            var matterViewModels = new List<MattersViewModel>();
            var inventories = _inventoryService.GetInventorysByUserId(userId);
            for (int i = 0; i < matters.Count; i++)
            {
                var timeToPastdue = TimeToPastdue(matters[i].UserId, matters[i].TypeId, matters[i].InventoryId, matters[i].MatterId);
                var inventory = inventories.SingleOrDefault(invent => invent.InventoryId == matters[i].InventoryId);
                var matterViewModel = new MattersViewModel()
                {
                    MatterId = matters[i].MatterId,
                    UserId = matters[i].UserId,
                    InventoryId = matters[i].InventoryId,
                    TypeId = matters[i].TypeId,
                    MatterContent = matters[i].MatterContent,
                    Remark = matters[i].Remark,
                    OverTime = matters[i].OverTime,
                    CreatTime = matters[i].CreatTime,
                    IsFinished = matters[i].IsFinished,
                    IsPastdue = matters[i].IsPastdue,
                    TimeToPastdue = timeToPastdue,
                    InventoryName = inventory.InventoryName
                };
                matterViewModels.Add(matterViewModel);
            }
            return matterViewModels;
        }
        public MattersViewModel ConvertEntityModelToViewModel(Matter matter)
        {
            var inventories = _inventoryService.GetInventorysByUserId(matter.UserId);
            var inventory = inventories.SingleOrDefault(invent => invent.InventoryId == matter.InventoryId);
            var matterViewModel = new MattersViewModel()
            {
                MatterId = matter.MatterId,
                UserId = matter.UserId,
                InventoryId = matter.InventoryId,
                TypeId = matter.TypeId,
                MatterContent = matter.MatterContent,
                Remark = matter.Remark,
                OverTime = matter.OverTime,
                CreatTime = matter.CreatTime,
                IsFinished = matter.IsFinished,
                IsPastdue = matter.IsPastdue,
                InventoryName = inventory.InventoryName
            };

            return matterViewModel;
        }

        /// <summary>
        /// 距离过期的天数
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="typeId"></param>
        /// <param name="inventoryId"></param>
        /// <param name="matterId"></param>
        /// <returns></returns>
        public int TimeToPastdue(int userId, int typeId, int inventoryId, int matterId)
        {
            var matter = GetMatter(matterId);
            if (matter.OverTime == null)
                return 0;
            else
            {
                TimeSpan days = ((DateTime)matter.OverTime).Subtract(DateTime.Now);
                return days.Days + 1;
            }

        }
        /// <summary>
        /// 搜索事项
        /// </summary>
        /// <param name="text"></param>
        /// <param name="matters"></param>
        /// <returns></returns>
        public List<MattersViewModel> SearchMatters(string text, List<Matter> matters)
        {
            var mattersContents = new List<string>();
            var mattersInclude = new List<MattersViewModel>();
            for (int i = 0; i < matters.Count; i++)
            {
                var content = matters[i].MatterContent;
                mattersContents.Add(content);
            }
            for (int i = 0; i < mattersContents.Count; i++)
            {
                if (mattersContents[i].Contains(text))
                {
                    var matter = matters[i];
                    var matterView = ConvertEntityModelToViewModel(matter);
                    mattersInclude.Add(matterView);
                };
            }
            return mattersInclude;
        }

        public DetailMatterModel GetDetailMatterModel(Matter matter)
        {
            var user = _userService.GetUserModel(matter.UserId);
            DetailMatterModel matterModel = new DetailMatterModel()
            {
                UserName = (user.NickName ?? user.UserName),
                TypeName = _typeService.GetType(matter.TypeId).TypeName,
                InventoryName = _inventoryService.GetInventoryById(matter.InventoryId).InventoryName,
                Matter = matter
            };
            return matterModel;
        }
    }
}
